import frappe
from light_mes.api import has_enable_workstation_employee_group_link


def job_card_before_insert(doc, method):
    if has_enable_workstation_employee_group_link():
        emp_list = frappe.get_all("Employee Group",
            filters = {"workstation": doc.workstation},
            fields = '`tabEmployee Group Table`.employee',
            as_list = 1
        )
        for emp in emp_list:
            doc.append("employee",
                {
                    "parenttype": "Job Card",
                    "parentfield": "employee",
                    "employee": emp[0]
                }
            )

def sync_employees_user_permission(doc, method):
    """
    删除或添加维护的员工对应的用户权限限制记录
    """    

    if doc.has_value_changed("employees"):
        before_save = doc.get_doc_before_save()
        old_employees = {r.employee for r in before_save.employees} if before_save else set()
        new_employees = {r.employee for r in doc.employees}
        employee_user_map = frappe._dict(frappe.get_all("Employee", 
            filters = {
                "name": ("in", old_employees.union(new_employees))
            },
            fields=["name", "user_id"],
            as_list=1
        ))
        for employee in (new_employees - old_employees):
            user = employee_user_map.get(employee)
            if user:
                frappe.get_doc({
                    "doctype": "User Permission",
                    "user": user,
                    "allow": doc.doctype,
                    "for_value": doc.name
                }).insert(ignore_permissions=True, ignore_if_duplicate=True)
        for employee in (old_employees - new_employees):
            user = employee_user_map.get(employee)
            if user:
                frappe.db.delete("User Permission", {
                    "user": user,
                    "allow": doc.doctype,
                    "for_value": doc.name
                })

def work_order_validate(doc, method):
    if doc.has_value_changed("bom_no") and hasattr(doc, "meter_per_roll"):
        meter = doc.qty if doc.stock_uom == "米" else 0
        roll = 0
        for row in doc.required_items:
            if row.stock_uom == "卷":
                roll = row.required_qty
                break
        if meter and roll:
            doc.meter_per_roll = meter / roll

def item_validate(doc, method):
    """
    将多规格物料的某个属性值回写到属性主数据设置的物料自定义字段
    """
    
    if doc.variant_of:
        custom_field = frappe.qb.DocType("Custom Field")
        item_attribute =  frappe.qb.DocType("Item Attribute")
        data = frappe.qb.from_(item_attribute
        ).join(custom_field
        ).on(custom_field.name == item_attribute.item_custom_field
        ).where(
            item_attribute.name.isin([r.attribute for r in doc.attributes])
        ).select(
            item_attribute.name,
            custom_field.fieldname
        ).run(as_list=1)
        attribute_field_map = frappe._dict(data)
        if attribute_field_map:
            for row in doc.attributes:
                field = attribute_field_map.get(row.attribute)
                if field:
                    doc.set(field, row.attribute_value)
